import { defineStore } from 'pinia'
import { resetRouter } from '@/router'
import { useTagsStore, usePermissionStore } from '@/store'
import { removeAllTokens, toLogin } from '@/utils'
import api from '@/api/admin.js'

export const useUserStore = defineStore('admin', {
  state() {
    return {
      adminInfo: {},
      showLoginModal: false,
    }
  },

  actions: {
    getUsername() {
      return this.adminInfo.username
    },
    getName() {
      return this.adminInfo.name
    },
    getId() {
      return this.adminInfo.id
    },
    getRole() {
      return this.adminInfo.role || []
    },
    // 获取Admin端用户账户信息
    async getAccountInfo() {
      const res = await api.getAccount()
      const { username, name, role, id } = res.data
      console.log(res)
      try {
        this.adminInfo = { username, name, role: [role], id }
        return Promise.resolve(res.data)
      } catch (error) {
        return Promise.reject(error)
      }
    },
    logout() {
      const { resetTags } = useTagsStore()
      resetTags()
      this.doLogout()
      toLogin()
    },
    doLogout() {
      const { resetPermission } = usePermissionStore()
      removeAllTokens() //删除所有的token
      resetPermission() // 重置权限（状态中的路由）
      resetRouter() // 重置所有（User和Admin）路由 （实际路由）
      this.$reset()
    },
    setAdminInfo(adminInfo = {}) {
      this.adminInfo = { ...this.adminInfo, ...adminInfo}
    },
    openLoginModal() {
      this.showLoginModal = true
    },
    closeLoginModal() {
      this.showLoginModal = false
    },
  },
})
